package com.returnsoft.softphone.eao;

import java.io.Serializable;
import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import com.returnsoft.softphone.entity.Peer;
import com.returnsoft.softphone.entity.Server;
import com.returnsoft.softphone.exception.EaoExcepcion;

@LocalBean
@Stateless
public class PeerEao implements Serializable{
	
	private static final long serialVersionUID = 1L;

	@PersistenceContext(name = "CCenterEJB", unitName = "CCenterEJB")
	private EntityManager em;
	
	

	public List<Peer> findAvailables(Integer serverId) throws EaoExcepcion {
		try {
			String query = "SELECT p FROM Peer p left join p.agent a left join p.server s WHERE a.id IS NULL AND s.id= :serverId";
			TypedQuery<Peer> q = em.createQuery(query, Peer.class);
			q.setParameter("serverId", serverId);
			List<Peer> peers = q.getResultList();
			return peers;
		} catch (Exception e) {
			e.printStackTrace();
			throw new EaoExcepcion(e.getMessage());
		}
	}

	public Peer findPeer(Integer agentId) throws EaoExcepcion {
		try {
			Query q = em
					.createQuery("SELECT p.id,p.name,p.password,p.protocol,s.id,s.ip,s.amiUser,s.amiPassword,s.amiPort "
							+ "FROM Peer p "
							+ "left join p.agent a "
							+ "left join p.server s " + "WHERE a.id = :agentId");
			q.setParameter("agentId", agentId);

			Object[] peerObject = (Object[]) q.getSingleResult();

			Integer id = (Integer) peerObject[0];
			String name = (String) peerObject[1];
			String password = (String) peerObject[2];
			String protocol = (String) peerObject[3];
			Integer serverId = (Integer) peerObject[4];
			String serverIp = (String) peerObject[5];
			String serverAmiUser = (String) peerObject[6];
			String serverAmiPassword = (String) peerObject[7];
			Integer serverAmiPort = (Integer) peerObject[8];

			Peer peer = new Peer();
			peer.setId(id);
			peer.setName(name);
			peer.setPassword(password);
			peer.setProtocol(protocol);

			if (serverId != null && serverId > 0) {
				Server server = new Server();
				server.setId(serverId);
				server.setIp(serverIp);
				server.setAmiUser(serverAmiUser);
				server.setAmiPassword(serverAmiPassword);
				server.setAmiPort(serverAmiPort);
				peer.setServer(server);
			}

			return peer;
		} catch (NoResultException e) {
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			throw new EaoExcepcion(e.getMessage());
		}
	}
	
	
	

}
